<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能数据助手</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: -apple 
-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
        }
        
        :root {
            --primary-color: #4361ee;
            --primary-light: #4895ef;
            --success-color: #2ecc71;
            --error-color: #e74c3c;
            --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #e4e7ec 100%);
            --card-gradient: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
        }

        body {
            background: var(--bg-gradient);
            padding: 30px;
            color: #2d3436;
            line-height: 1.6;
            min-height: 100vh;
        }

        .container {
            max-width: 1100px;
            margin: 0 auto;
            background: var(--card-gradient);
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            padding: 30px;
            transition: all 0.3s ease;
        }

        .container:hover {
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
            transform: translateY(-2px);
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
            font-size: 2.5em;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .input-section, .output-section, .result-section {
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            transition: all 0.3s ease;
        }

        .input-section:hover, .output-section:hover, .result-section:hover {
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 1.1em;
        }

        textarea {
            width: 100%;
            min-height: 120px;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            resize: vertical;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        textarea:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }

        button {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            border: none;
            padding: 12px 24px;
            cursor: pointer;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        button:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.2);
        }

        button:active {
            transform: translateY(1px);
        }

        button:disabled {
            background: #e9ecef;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        pre {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            overflow-x: auto;
            border: 2px solid #e9ecef;
            min-height: 120px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.5;
            transition: all 0.3s ease;
        }

        pre:hover {
            border-color: var(--primary-light);
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
            padding: 20px;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(5px);
            animation: fadeIn 0.3s ease;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid rgba(67, 97, 238, 0.1);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .error-message {
            color: var(--error-color);
            margin-top: 10px;
            font-weight: 600;
            display: none;
            padding: 12px;
            border-radius: 8px;
            background: rgba(231, 76, 60, 0.1);
            animation: fadeIn 0.3s ease;
        }

        .execute-btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
        }

        .success-message {
            color: var(--success-color);
            margin-top: 10px;
            display: none;
            text-align: center;
            padding: 12px;
            border-radius: 8px;
            background: rgba(46, 204, 113, 0.1);
            animation: fadeIn 0.3s ease;
        }

        /* 结果表格样式 */
        .result-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            margin-top: 15px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
        }

        .result-table th, .result-table td {
            border: 1px solid #e9ecef;
            padding: 12px 15px;
            text-align: left;
        }

        .result-table th {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            font-weight: 600;
            color: #2c3e50;
            position: sticky;
            top: 0;
            z-index: 1;
        }

        .result-table tr {
            transition: all 0.3s ease;
        }

        .result-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        .result-table tr:hover {
            background-color: #f1f3f5;
            transform: scale(1.002);
        }

        /* 分页和下载按钮样式 */
        .result-controls {
            margin-top: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-btn {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 6px;
            cursor: pointer;
            width: auto;
            margin-top: 0;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .page-btn:disabled {
            background: #e9ecef;
            cursor: not-allowed;
        }

        #page-info {
            color: #2c3e50;
            font-weight: 500;
        }

        .download-controls {
            display: flex;
            gap: 15px;
        }

        .download-btn {
            background: linear-gradient(135deg, var(--success-color), #27ae60);
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 6px;
            cursor: pointer;
            width: auto;
            margin-top: 0;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .download-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.2);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .container {
                padding: 20px;
            }

            .result-controls {
                flex-direction: column;
                gap: 15px;
            }

            .pagination, .download-controls {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <!-- HTML结构保持不变 -->
    <div class="container">
        <h1>智能数据助手</h1>
        
        <div class="input-section">
            <label for="user-input">请输入您的需求描述：</label>
            <textarea id="user-input" placeholder="例如：查询所有年龄大于30岁的用户信息"></textarea>
            <button id="generate-btn">
                <span>生成SQL</span>
            </button>
        </div>
        
        <div class="loading">
            <div class="loading-spinner"></div>
            <p>正在处理，请稍候...</p>
        </div>
        
        <div class="error-message" id="error-message"></div>
        
        <div class="output-section">
            <label for="sql-output">生成的SQL：</label>
            <pre id="sql-output"></pre>
            <button id="execute-btn" class="execute-btn">
                <span>执行SQL</span>
            </button>
        </div>

        <div class="result-section">
            <label for="result-output">执行结果：</label>
            <div id="result-output"></div>
            <div class="result-controls" style="display: none;">
                <div class="pagination">
                    <button id="prev-page" class="page-btn">&lt; 上一页</button>
                    <span id="page-info">第 1 页，共 1 页</span>
                    <button id="next-page" class="page-btn">下一页 &gt;</button>
                </div>
                <div class="download-controls">
                    <button id="download-csv" class="download-btn">
                        <span>下载 CSV</span>
                    </button>
                    <button id="download-excel" class="download-btn">
                        <span>下载 Excel</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const userInput = document.getElementById('user-input');
            const generateBtn = document.getElementById('generate-btn');
            const executeBtn = document.getElementById('execute-btn');
            const sqlOutput = document.getElementById('sql-output');
            const resultOutput = document.getElementById('result-output');
            const loading = document.querySelector('.loading');
            const errorMessage = document.getElementById('error-message');
            
            let currentPage = 1;
            let pageSize = 10;
            let allResults = [];
            
            // 分页显示函数
            function displayPage(page, data) {
                const start = (page - 1) * pageSize;
                const end = start + pageSize;
                const pageData = data.slice(start, end);
                const totalPages = Math.ceil(data.length / pageSize);
                
                // 更新页码信息
                document.getElementById('page-info').textContent = 
                    `第 ${page} 页，共 ${totalPages} 页 (共 ${data.length} 条记录)`;
                
                // 更新按钮状态
                document.getElementById('prev-page').disabled = page === 1;
                document.getElementById('next-page').disabled = page === totalPages;
                
                // 创建表格
                createTable(pageData);
            }

            // 创建表格函数
            function createTable(data) {
                resultOutput.innerHTML = '';
                if (!data || data.length === 0) {
                    resultOutput.textContent = '查询结果为空';
                    return;
                }

                const table = document.createElement('table');
                table.className = 'result-table';
                
                // 添加表头
                const thead = document.createElement('thead');
                const headerRow = document.createElement('tr');
                Object.keys(data[0]).forEach(key => {
                    const th = document.createElement('th');
                    th.textContent = key;
                    headerRow.appendChild(th);
                });
                thead.appendChild(headerRow);
                table.appendChild(thead);
                
                // 添加数据行
                const tbody = document.createElement('tbody');
                data.forEach(row => {
                    const tr = document.createElement('tr');
                    Object.values(row).forEach(value => {
                        const td = document.createElement('td');
                        td.textContent = value;
                        tr.appendChild(td);
                    });
                    tbody.appendChild(tr);
                });
                table.appendChild(tbody);
                
                resultOutput.appendChild(table);
            }

            // 下载 CSV 函数
            function downloadCSV() {
                if (!allResults.length) return;
                
                const headers = Object.keys(allResults[0]);
                const csv = [
                    headers.join(','),
                    ...allResults.map(row => 
                        headers.map(field => 
                            JSON.stringify(row[field] || '')
                        ).join(',')
                    )
                ].join('\n');
                
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', 'query_results.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }

            // 下载 Excel 函数
            function downloadExcel() {
                if (!allResults.length) return;
                
                const headers = Object.keys(allResults[0]);
                let excel = '<table><tr>';
                
                // 添加表头
                headers.forEach(header => {
                    excel += `<th>${header}</th>`;
                });
                excel += '</tr>';
                
                // 添加数据行
                allResults.forEach(row => {
                    excel += '<tr>';
                    headers.forEach(field => {
                        excel += `<td>${row[field] || ''}</td>`;
                    });
                    excel += '</tr>';
                });
                excel += '</table>';
                
                const blob = new Blob([excel], {type: 'application/vnd.ms-excel'});
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', 'query_results.xls');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
            
            // 生成SQL的点击事件
            generateBtn.addEventListener('click', async function() {
                const query = userInput.value.trim();
                
                if (!query) {
                    showError('请输入需求描述！');
                    return;
                }
                
                // 重置界面
                sqlOutput.textContent = '';
                resultOutput.innerHTML = '';
                hideError();
                
                // 显示加载中
                loading.style.display = 'block';
                generateBtn.disabled = true;
                
                try {
                    const response = await fetch('/api/query', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ user_input: query })
                    });
                    
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.error || '生成SQL失败');
                    }
                    
                    sqlOutput.textContent = data.sql || 'API返回了空结果';
                    
                } catch (error) {
                    showError('错误: ' + error.message);
                } finally {
                    loading.style.display = 'none';
                    generateBtn.disabled = false;
                }
            });
            
            // 执行SQL的点击事件
            executeBtn.addEventListener('click', async function() {
                const sql = sqlOutput.textContent;
                
                if (!sql || sql === 'API返回了空结果') {
                    showError('没有可执行的SQL语句！');
                    return;
                }
                
                // 重置结果区域
                resultOutput.innerHTML = '';
                hideError();
                
                // 显示加载中
                loading.style.display = 'block';
                executeBtn.disabled = true;
                
                try {
                    const response = await fetch('/api/execute', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ sql: sql })
                    });
                    
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.error || '执行SQL失败');
                    }
                    
                    if (data.results && data.results.length > 0) {
                        allResults = data.results;
                        currentPage = 1;
                        document.querySelector('.result-controls').style.display = 'flex';
                        displayPage(currentPage, allResults);
                    } else {
                        resultOutput.textContent = '查询结果为空';
                        document.querySelector('.result-controls').style.display = 'none';
                    }
                    
                } catch (error) {
                    showError('错误: ' + error.message);
                } finally {
                    loading.style.display = 'none';
                    executeBtn.disabled = false;
                }
            });
            
            // 显示错误信息
            function showError(message) {
                errorMessage.textContent = message;
                errorMessage.style.display = 'block';
            }
            
            // 隐藏错误信息
            function hideError() {
                errorMessage.style.display = 'none';
            }
            
            // 按下Enter键也可以提交
            userInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && e.ctrlKey) {
                    generateBtn.click();
                }
            });

            // 分页按钮事件监听
            document.getElementById('prev-page').addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    displayPage(currentPage, allResults);
                }
            });

            document.getElementById('next-page').addEventListener('click', () => {
                if (currentPage < Math.ceil(allResults.length / pageSize)) {
                    currentPage++;
                    displayPage(currentPage, allResults);
                }
            });

            // 下载按钮事件监听
            document.getElementById('download-csv').addEventListener('click', downloadCSV);
            document.getElementById('download-excel').addEventListener('click', downloadExcel);
        });
    </script>
</body>
</html>